import type { SiteBaseInfo } from '@/apis/model/site'
import {
  deleteApiSiteApi,
  getApiSiteDetailApi,
  updateApiSiteApi,
  updateApiSiteResolveStatusApi
} from '@/apis/modules/site/site'
import ContentContainer from '@/components/ContentContainer.vue'
import EditCname from '@/components/EditCname.vue'
import EditField from '@/components/EditField.vue'
import { Descriptions, Switch, type DescData } from '@arco-design/web-vue'
import IconsDelete from '~icons/icons/delete'
import IconsEdit from '~icons/icons/edit'
import IconsRefresh from '~icons/icons/refresh'
import IconsSuccess from '~icons/icons/success'
import IconsWarning from '~icons/icons/warning'
import useGroupArea from '../../hooks/useGroupArea'

export default defineComponent({
  setup() {
    const { visible, open } = usePopup()
    const router = useRouter()
    const route = useRoute()
    const { areaListOptions, siteGroupOptions } = useGroupArea()
    const id = computed(() => route.params.id as string)
    const baseInfo = ref<SiteBaseInfo>()
    const data = ref<DescData[]>([])
    const loading = ref(false)
    const statusLoading = ref(false)
    const getBaseInfo = () => {
      loading.value = true
      getApiSiteDetailApi({ id: id.value })
        .then((res) => {
          baseInfo.value = res
          setData(baseInfo.value)
        })
        .finally(() => {
          loading.value = false
        })
    }
    const updateBaseInfo = async (record: SiteBaseInfo) => {
      await updateApiSiteApi({ id: id.value, ...record })
      getBaseInfo()
    }

    const changeStatus = (record: SiteBaseInfo) => {
      statusLoading.value = true
      updateApiSiteApi({ id: id.value, ...record })
        .then(() => {
          //baseInfo.value!.resolve_info!.resolve_status = res.resolve_status
        })
        .catch(() => {
          baseInfo.value!.status = record.status === 1 ? 2 : 1
        })
        .finally(() => {
          statusLoading.value = false
        })
    }
    const getResolveStatus = () => {
      loading.value = true
      updateApiSiteResolveStatusApi({ id: id.value })
        .then((res) => {
          baseInfo.value!.resolve_info!.resolve_status = res.resolve_status
        })
        .finally(() => {
          loading.value = false
        })
    }
    const deleteSite = () => {
      const fn = () =>
        deleteApiSiteApi({ id: id.value }).then(() => {
          ToastUtils.success('删除成功')
          router.replace({ name: 'SiteList' })
        })

      CloudModal.error(
        {
          content: '该操作会删除此站点，确认删除？',
          okText: '删除'
        },
        fn
      )
    }
    const setData = (info: SiteBaseInfo) => {
      data.value = [
        {
          label: 'CNAME域名',
          value: () => (
            <div class="resolve-status">
              {info.resolve_info?.resolve_value}
              <IconsEdit class="refresh" onClick={open} />
            </div>
          ),
          span: 1
        },
        {
          label: '启用状态',
          value: () => (
            <div class="min-w-60">
              <Switch
                v-model={info.status}
                checked-value={1}
                unchecked-value={2}
                size="small"
                loading={statusLoading.value}
                onChange={(v) => {
                  changeStatus({ status: v as 1 | 2 })
                }}
              />
            </div>
          ),
          span: 1
        },
        {
          label: '接入状态',
          value: () => {
            return (
              <div class="resolve-status">
                {info.resolve_info?.resolve_status === 1
                  ? h(IconsSuccess)
                  : h(IconsWarning)}
                {info.resolve_info?.resolve_status === 1 ? '已接入' : '未接入'}
                <IconsRefresh class="refresh" onClick={getResolveStatus} />
              </div>
            )
          },
          span: 1
        },
        {
          label: '分组',
          value: () => (
            <EditField
              edit-title="编辑分组"
              defaultValue={info.group_info?.id}
              type="select"
              fn={updateBaseInfo}
              hide-asterisk
              field="group_id"
              placeholder="请选择分组"
              options={siteGroupOptions.value}
              label="选择分组"
              mouseOver
              content={info.group_info?.name}
            />
          ),
          span: 1
        },
        {
          label: '区域',
          value: () => (
            <section class='!w-80'>
              <EditField
                edit-title="编辑区域"
                defaultValue={info.region_info?.id}
                type="select"
                field="region_id"
                hide-asterisk
                fn={updateBaseInfo}
                placeholder="请选择区域"
                label="选择区域"
                options={areaListOptions.value}
                mouseOver
                content={info.region_info?.name}
              />
            </section>
          ),
          span: 1
        },
        {
          label: '添加时间',
          value: formatUnix(info.created_at),
          span: 1
        },
        {
          label: '备注',
          value: () => (
            <div class="max-w-80">
              <EditField
                edit-title="编辑备注"
                defaultValue={info.remark}
                type="input"
                field="remark"
                hide-asterisk
                maxLength={20}
                fn={updateBaseInfo}
                placeholder="请输入备注"
                required={false}
                label="备注"
                mouseOver
                content={info.remark}
              />
            </div>
          ),
          span: 3
        }
      ]
    }

    watchEffect(() => {
      getBaseInfo()
    })
    return () => (
      <ContentContainer
        show-pagination={false}
        show-footer={false}
        loading={loading.value}
        refresh={false}
        inner
        class="site-base-info">
        {{
          header: () => (
            <div class="flex justify-between items-center w-full">
              <span class="text-2 text-lg font-bold">
                {baseInfo.value?.domain}
              </span>

              <a-link
                status="danger"
                class="flex gap-x-1 py-2! px-4!"
                onClick={deleteSite}>
                <IconsDelete />
                删除站点
              </a-link>
            </div>
          ),
          default: () => (
            <>
              <Descriptions data={data.value} class='!text-4 ' />
              <EditCname
                modelValue={visible.value}
                siteBase={true}
                record={{
                  site_id: id.value,
                  siteName: baseInfo.value?.domain,
                  resolve_domain_id:
                    baseInfo.value?.resolve_info?.resolve_domain_id,
                  cname: baseInfo.value?.resolve_info?.resolve_name
                }}
                onReload={getBaseInfo}
                onUpdate:modelValue={(v) => {
                  visible.value = v
                }}></EditCname>
            </>
          )
        }}
      </ContentContainer>
    )
  }
})
